02. Java to JavaScript Comparison

In this lesson we'll be writing JavaScript code. It helps to already have experience writing JavaScript, but we'll be stepping you through each line of code to write. You have enough programming experience with Java to understand the code in this lesson. Below you'll find a quick reference of the syntactic and semantic differences between Java and JavaScript. If you'd like to learn more about JavaScript, consider taking the JavaScript Basics course.

Comparison of Java and JavaScript:

Type

Find out more about types here.

Java: Static Type

Variables are associated with a type:

String name = "Firebase";
name = 3; // ERROR

JavaScript: Dynamic Type

Variables are not associated with a type

var name = "Firebase";
name = 3; // OK

Constants

Java:

final x = 42;
x = 1024; // ERROR
const x = 42;
x = 1024 // ERROR

Semicolons at the end of statements?

Java: Semicolons at the end of statements

int x = 42;

JavaScript:

Optional semicolons

var x = 42 // OK
var y = 1024; // Also OK

Logging to the console/debug area

Java:

System.out.println("Message");

// Android-specific
Log.d(TAG, "Message");

JavaScript:

console.log("Message");

Typesafe Equality

Java:

== for primitives, .equals() for objects

JavaScript:

=== for strict equality

Pushing values to arrays

Java:

ArrayList arrayList = new ArrayList<>();
arrayList.add(10);

JavaScript:

var array = [];
array.push(10);

Method/Function syntax

Java:

public int multiply(int a, int b) {
  return a * b;
}

JavaScript:

Function declaration:

function multiply(a, b) {
    return a * b;
}

or, function expression:

// Variable assignment
var multiply = function(a, b) {
  return a  b;
}

or, arrow function

// New in ES2016; drops "function" keyword
var multiply = (a ,b) => {
  return a  b;
}

Strings

Java:

Only double quotes represent strings:

String name = "Firebase";

JavaScript:

Double and single quotes represent strings:

var str1 = "this is a valid string";
var str2 = 'and this is too';

String interpolation with backtick quotes and ${}:

var name = 'puf';
var message = `Hello ${name}!`; // Hello puf!

Loops

Java:

String[] list = {"apple", "pear", "orange"};

for (int i = 0; i < list.length; i++) {
    System.out.println(list[i]);
}

JavaScript:

var list = ['apple', 'pear', 'orange'];

for (i = 0; i < list.length(); i++) {
console.log(list[i]);
}

Or

for (var index in list) {
     console.log(list[index])
}

Importing a library

Java:

import java.util.ArrayList;

JavaScript:

Use require() and assign the result to a variable for later use:

var child_process = require('child_process');